from flask import Flask, request, send_file
import os
import socket
from testPspSleepV3Demo import run_upload
from sleepPng import generate_png

from zeroconf import ServiceInfo, Zeroconf, NonUniqueNameException
import time

app = Flask(__name__)

# 创建目录
os.makedirs("./uploaded", exist_ok=True)
os.makedirs("./received_from_server", exist_ok=True)

@app.route("/upload", methods=["POST"])
def upload():
    file = request.files.get("file")
    if not file:
        return {"error": "no file"}, 400

    # -------- 清空 uploaded 目录旧 TXT 文件 --------
    uploaded_dir = "./uploaded"
    for f in os.listdir(uploaded_dir):
        if f.endswith(".txt"):
            try:
                os.remove(os.path.join(uploaded_dir, f))
                print(f"[server] 已删除旧文件: {f}")
            except Exception as e:
                print(f"[server] 删除文件出错: {f}, {e}")
    # ---------------------------------------------

    # 保存新上传的文件
    file_path = os.path.join(uploaded_dir, file.filename)
    file.save(file_path)
    print(f"[server] 文件已保存到 uploaded: {file_path}")

    # 调用 run_upload 上传到原服务器，返回新的 txt
    returned_txt = run_upload(file_path)
    if not returned_txt:
        return {"error": "server upload failed"}, 500

    # 生成 PNG
    png_path = generate_png(returned_txt)
    print(f"[server] PNG 已生成: {png_path}")
    return send_file(png_path, as_attachment=True)

# @app.route("/upload", methods=["POST"])
# def upload():
#     file = request.files.get("file")
#     if not file:
#         return {"error": "no file"}, 400
#
#     file_path = os.path.join("./uploaded", file.filename)
#     file.save(file_path)
#     print(f"[server] 文件已保存到 uploaded: {file_path}")
#
#     # 调用 run_upload 上传到原服务器，返回新的 txt
#     returned_txt = run_upload(file_path)
#     if not returned_txt:
#         return {"error": "server upload failed"}, 500
#
#     # 生成 PNG
#     png_path = generate_png(returned_txt)
#     print(f"[server] PNG 已生成: {png_path}")
#     return send_file(png_path, as_attachment=True)

# ----------------- Zeroconf 服务注册 -----------------
def get_local_ip():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        # 连接到公网IP获取本地IP
        s.connect(("8.8.8.8", 80))
        ip = s.getsockname()[0]
    except Exception:
        ip = "127.0.0.1"
    finally:
        s.close()
    return ip

def register_zeroconf_service(port=8080, service_name="SleepServer"):
    zeroconf = Zeroconf()
    ip_addr = socket.inet_aton(get_local_ip())
    full_name = f"{service_name}._http._tcp.local."
    info = ServiceInfo(
        "_http._tcp.local.",
        full_name,
        addresses=[ip_addr],
        port=port,
        properties={},
        server=f"{service_name}.local."
    )

    # 尝试注册服务，如果名字冲突自动加时间戳
    attempt = 0
    while True:
        try:
            zeroconf.register_service(info)
            print(f"[Zeroconf] 服务已注册: {full_name}, IP: {get_local_ip()}:{port}")
            break
        except NonUniqueNameException:
            attempt += 1
            full_name = f"{service_name}-{int(time.time())}-{attempt}._http._tcp.local."
            info.name = full_name
            print(f"[Zeroconf] 名称冲突，改用新服务名: {full_name}")

    return zeroconf, info

if __name__ == "__main__":
    zeroconf, info = register_zeroconf_service(port=8080)
    try:
        app.run(host="0.0.0.0", port=8080, debug=True)
    finally:
        zeroconf.unregister_service(info)
        zeroconf.close()
